package com.atguigu.srb.core.service.impl;

import com.atguigu.common.exception.Assert;
import com.atguigu.common.result.ResponseEnum;
import com.atguigu.srb.core.enums.BorrowInfoStatusEnum;
import com.atguigu.srb.core.enums.BorrowerStatusEnum;
import com.atguigu.srb.core.enums.UserBindEnum;
import com.atguigu.srb.core.mapper.BorrowerMapper;
import com.atguigu.srb.core.mapper.IntegralGradeMapper;
import com.atguigu.srb.core.mapper.UserInfoMapper;
import com.atguigu.srb.core.pojo.entity.BorrowInfo;
import com.atguigu.srb.core.mapper.BorrowInfoMapper;
import com.atguigu.srb.core.pojo.entity.Borrower;
import com.atguigu.srb.core.pojo.entity.IntegralGrade;
import com.atguigu.srb.core.pojo.entity.UserInfo;
import com.atguigu.srb.core.pojo.vo.BorrowInfoApprovalVO;
import com.atguigu.srb.core.pojo.vo.BorrowerApprovalVO;
import com.atguigu.srb.core.pojo.vo.BorrowerDetailVO;
import com.atguigu.srb.core.service.BorrowInfoService;
import com.atguigu.srb.core.service.BorrowerService;
import com.atguigu.srb.core.service.DictService;
import com.atguigu.srb.core.service.LendService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sun.xml.bind.v2.TODO;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 借款信息表 服务实现类
 * </p>
 *
 * @author Dragon
 * @since 2021-07-29
 */
@Service
public class BorrowInfoServiceImpl extends ServiceImpl<BorrowInfoMapper, BorrowInfo> implements BorrowInfoService {

    @Resource
    private LendService lendService;
    @Resource
    private DictService dictService;
    @Resource
    UserInfoMapper userInfoMapper;

    @Resource
    private BorrowerMapper borrowerMapper;

    @Resource
    private BorrowerService borrowerService;
    @Resource
    IntegralGradeMapper integralGradeMapper;

    @Override
    public BigDecimal getBorrowerAmount(Long userId) {
        //获取积分数量
        UserInfo userInfo = userInfoMapper.selectById(userId);
        Assert.notNull(userInfo, ResponseEnum.LOGIN_MOBILE_ERROR);
        Integer integral = userInfo.getIntegral();

        //根据积分查询借款额度
        QueryWrapper<IntegralGrade> QueryWrapper = new QueryWrapper<>();
        QueryWrapper.le("integral_start", integral);
        QueryWrapper.ge("integral_end", integral);
        IntegralGrade integralGrade = integralGradeMapper.selectOne(QueryWrapper);
        if (integralGrade==null) {
            return  new BigDecimal("0");
        }
        return integralGrade.getBorrowAmount();
    }

    @Override
    public void saveBorrowerInfo(BorrowInfo borrowInfo, Long userId) {
        UserInfo userInfo = userInfoMapper.selectById(userId);
      //判断用户绑定状态
        Assert.isTrue(userInfo.getBindStatus().intValue()== UserBindEnum.BIND_OK.getStatus().intValue(),ResponseEnum.USER_NO_BIND_ERROR);
       //判断用户信息是否审批通过
        Assert.isTrue(userInfo.getBorrowAuthStatus().intValue()== BorrowerStatusEnum.AUTH_OK.getStatus().intValue(),ResponseEnum.USER_NO_AMOUNT_ERROR);
       //判断借款额度是否足够
         BigDecimal borrowAmount = this.getBorrowerAmount(userId);
         Assert.isTrue(borrowInfo.getAmount().doubleValue() <= borrowAmount.doubleValue(),ResponseEnum.USER_AMOUNT_LESS_ERROR );

      borrowInfo.setUserId(userId);
      borrowInfo.setBorrowYearRate(borrowInfo.getBorrowYearRate().divide(new BigDecimal(100)));
      borrowInfo.setStatus(BorrowInfoStatusEnum.CHECK_RUN.getStatus());
      baseMapper.insert(borrowInfo);
    }

    @Override
    public Integer getBorrowerStatusByUserId(Long userId) {
        QueryWrapper<BorrowInfo> QueryWrapper = new QueryWrapper<>();
        QueryWrapper.select("status").eq("user_id",userId);
        BorrowInfo borrowInfo = baseMapper.selectOne(QueryWrapper);
        if (borrowInfo==null) {
            return BorrowInfoStatusEnum.NO_AUTH.getStatus();
        }
        return borrowInfo.getStatus();
    }

    @Override
    public List<BorrowInfo> selectList() {
        List<BorrowInfo> borrowInfoList =  baseMapper.selectBorrowInfoList();
          borrowInfoList.forEach(borrowInfo -> {
              String returnMethod = dictService.getNameByParentDictCodeAndValue("returnMethod", borrowInfo.getReturnMethod());
              String moneyUse = dictService.getNameByParentDictCodeAndValue("moneyUse", borrowInfo.getMoneyUse());
              String status = BorrowInfoStatusEnum.getMsgByStatus(borrowInfo.getStatus());
              borrowInfo.getParam().put("returnMethod",returnMethod);
              borrowInfo.getParam().put("moneyUse",moneyUse);
              borrowInfo.getParam().put("status",status);
          });

        return borrowInfoList;
    }

    @Override
    public Map<String, Object> getBorrowerInfoDetail(Long id) {
        BorrowInfo borrowInfo = baseMapper.selectById(id);

        String returnMethod = dictService.getNameByParentDictCodeAndValue("returnMethod", borrowInfo.getReturnMethod());
        String moneyUse = dictService.getNameByParentDictCodeAndValue("moneyUse", borrowInfo.getMoneyUse());
        String status = BorrowInfoStatusEnum.getMsgByStatus(borrowInfo.getStatus());
        borrowInfo.getParam().put("returnMethod",returnMethod);
        borrowInfo.getParam().put("moneyUse",moneyUse);
        borrowInfo.getParam().put("status",status);

        QueryWrapper<Borrower> QueryWrapper = new QueryWrapper<>();
         QueryWrapper.eq("user_id",borrowInfo.getUserId());
        Borrower borrower = borrowerMapper.selectOne(QueryWrapper);
        BorrowerDetailVO borrowerDetailVOById = borrowerService.getBorrowerDetailVOById(borrower.getId());
        Map<String, Object> HashMap = new HashMap<>();
        HashMap.put("borrowInfo",borrowInfo);
        HashMap.put("borrower",borrowerDetailVOById);

        return HashMap;
    }
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void approval(BorrowInfoApprovalVO borrowInfoApprovalVO) {
       //修改借款信息状态
        Long id = borrowInfoApprovalVO.getId();
        BorrowInfo borrowInfo = baseMapper.selectById(id);
        borrowInfo.setStatus(borrowInfoApprovalVO.getStatus());
        //审核通过则创建标的
       baseMapper.updateById(borrowInfo);
        if (borrowInfoApprovalVO.getStatus().intValue()==BorrowInfoStatusEnum.CHECK_OK.getStatus().intValue()){
            //创建标的

            lendService.createLend(borrowInfoApprovalVO,borrowInfo);
        }
    }
}
